<template>
	<statusBarVue title="我的公益" :isShowBar="true" :isShowLeft="true" />
	<view class="public-welfare-page" :style="pageHaveBarStyle">
		<uni-forms ref="baseForm" class="form" :modelValue="baseFormData" :rules="rules" label-position="top"
			label-width="200" :border="false">
			<view class="public-welfare-page-group">
				<uni-forms-item label="现场照片、视频" name="photo" required>
					<uni-file-picker title="您可以上传照片、视频、word文档、pdf文档等相关附件" v-model="baseFormData.photo"
						fileMediatype="image" mode="grid" @select="select" :limit="fileLimit">
						<view class="add-img-icon-group">
							<image src="/static/images/icon/add-images.png" class="add-img-icon">
							</image>
							<view class="add-img-text">点击上传</view>
						</view>
					</uni-file-picker>
				</uni-forms-item>

				<button @click="handleUploadVideo">
					上传视频
				</button>


				<view class="example-group">
					<view class="tit">
						现场照片示例图
					</view>
					<view class="imgs" @click="handlePreviewImage(exportsList)">
						<image class="img" v-for="(v, i) in exportsList" :key="'exportsList - ' + i" :src="v"></image>
					</view>
				</view>
			</view>

			<view class="public-welfare-page-group forms-item-line">
				<uni-forms-item class="lt" label="你在哪里" name="area" required>
				</uni-forms-item>

				<view class="rt" @click="handleGetArea">
					<view>{{currentLocationAreaText}}</view>
					<uni-icons type="right" size="19" color="#7E7E7E"></uni-icons>
				</view>
			</view>

			<view class="public-welfare-page-group">
				<uni-forms-item label="详细描述" name="description" required>
					<uni-easyinput class="input" type="textarea" maxlength="200" v-model="baseFormData.description"
						placeholder="请描述问题发生的地点，情况，也可以输入语音文件描述我们会尽快安排管理人员进行处理，处理后平台会对您进行积分奖励，感谢您为城市安全做出的贡献。"
						primaryColor="#22A366" />
				</uni-forms-item>
			</view>

			<view class="public-welfare-page-group">
				<uni-forms-item label="问题类型" name="problemType" required>
					<uni-data-checkbox mode="tag" v-model="baseFormData.problemType" selectedColor="#22A366"
						:localdata="typeList"></uni-data-checkbox>
				</uni-forms-item>
			</view>
		</uni-forms>
		<view class="submit">
			<button class="btn-submit" @click="handleSubmit">提交</button>
		</view>
	</view>
	<canvas id="myCanvas" type="2d"
		:style="{  width: canvasWidthValue + 'px', height: canvasHeightValue + 'px', position: 'fixed' }"
		style=" left:9000px;"></canvas>

</template>

<script>
	import statusBarVue from '@/components/statusBar.vue';

	import {
		publics
	} from '@/mixins/publics.js';

	import {
		postVideoProcess,
		postWorksheetPublic,
		getTypeList
	} from '@/utils/api.js';

	import tool_oss from '@/utils/oss';

	export default {
		mixins: [publics],
		components: {
			statusBarVue
		},
		data() {
			return {
				canvasWidthValue: 0,
				canvasHeightValue: 0,
				fileLimit: 1,
				// 现场照片示例图
				exportsList: [
					"https://shuidianbang.oss-cn-chengdu.aliyuncs.com/ceshi/e26a074c-5bc2-4bdb-b44e-13824a262cf8.png",
					"https://shuidianbang.oss-cn-chengdu.aliyuncs.com/ceshi/8c9cdf03-80a6-4d94-8577-8de958bc0356.png",
					"https://shuidianbang.oss-cn-chengdu.aliyuncs.com/ceshi/ad77adcd-b5e3-4f4d-905e-747de12438f9.png",
					"https://shuidianbang.oss-cn-chengdu.aliyuncs.com/ceshi/b7e3ac3a-f148-42f8-8db6-1575ff72332c.png"
				],
				// 基础表单数据
				baseFormData: {
					photo: [],
					deadline: null
				},
				// 校验规则
				rules: {
					area: {
						rules: [{
							required: true,
							errorMessage: '请打开设备GPS获取位置信息'
						}]
					},
					description: {
						rules: [{
							required: true,
							errorMessage: '详细描述不能为空'
						}]
					},
					problemType: {
						rules: [{
							required: true,
							errorMessage: '问题类型不能为空'
						}]
					},

					photo: {
						rules: [{
							required: true,
							errorMessage: '附件不能为空'
						}]
					}
				},
				typeList: []
			}
		},
		watch: {
			latitude(n, o) {
				console.log("n ------>>>", n)
				this.baseFormData.area = this.currentLocationAreaText;
			},
			currentLocationAreaText(n, o) {
				console.log("  currentLocationAreaText     n ------>>>", n)
			}
		},
		created() {
			this.getLocation();
			this.axiosGetTypeListApi();
		},
		methods: {
			axiosGetTypeListApi(){
				getTypeList().then(res => {
					this.typeList = res.type_list
				})
			},
			
			handleUploadVideo() {
				const _this = this;
				wx.authorize({
					scope: 'scope.writePhotosAlbum', // 请求相册权限
					success() {
						console.log('用户同意授权，可以使用相册')
						// 执行后续操作，例如调用chooseVideo
						wx.chooseVideo({
							sourceType: ['album', 'camera'],
							maxDuration: 30,
							camera: 'back',
							success(res) {
								console.log('upload ---->>>>', res)
								const tempFilePath = res.tempFilePath; // 获取到视频文件的临时路径

								// 在这里可以进行视频上传
								_this.uploadVideo(res, tempFilePath);
							},
							fail(error) {
								console.log(error);
							}
						});

					},
					fail() {
						uni.showToast({
							icon: 'error',
							title: '用户拒绝授权'
						})
					}
				})
			},

			uploadVideo(tempFile, tempFilePath) {
				console.log("tempFilePath ------->>>", tempFilePath)
				const _this = this;
				uni.showLoading({
					title: '上传并解析中。。。',
					mask: true
				});
				tool_oss.oss.upload([tempFile]).then(res => {
					console.log("tool-res ------>>>", res)
					_this.baseFormData.photo = {
						name: res.fileUploadSuccessObj.name,
						url: res.fileUploadSuccessObj.url
					};
					postVideoProcess({
						vfs: res.fileUploadSuccessObj.url,
						// vfs: 'https://shuidianbang.oss-cn-chengdu.aliyuncs.com/test/6%E6%9C%8829%E6%97%A5.mp4'
					}).then(res => {
						const {
							content,
							origin,
							scenes
						} = {
							...res
						};
						_this.baseFormData.description = content;

						_this.typeList.filter(item => {
							if (item.text === scenes) {
								_this.baseFormData.problemType = item.value
							}
						});
					}).catch(req => {
						uni.showToast({
							icon: 'none',
							title: req.error
						})
					}).finally(() => {
						uni.hideLoading();
					})
				})

			},

			// 打开地图
			async handleGetArea() {
				await this.getLocation();

				const {
					latitude,
					longitude,
					currentLocationAreaText
				} = this;
				uni.openLocation({
					latitude,
					longitude,
					address: currentLocationAreaText,
					success: function() {
						console.log('success');
					}
				});
			},

			// 获取位置信息
			getLocation() {
				uni.getLocation({
					type: 'gcj02', // 获取经纬度
					isHighAccuracy: true,
					highAccuracyExpireTime: 5000,
					success: res => {
						const {
							latitude,
							longitude
						} = res;
						this.latitude = latitude;
						this.longitude = longitude;
						this.location = `纬度: ${latitude}, 经度: ${longitude}`
						this.baseFormData.area = `纬度: ${latitude}, 经度: ${longitude}`;
						this.getLocationByCoordinates(latitude, longitude)
					},
					fail: () => {
						uni.showToast({
							title: '无法获取位置',
							icon: 'error',
						});
					}
				});
			},

			// 获取上传状态
			select(e) {
				console.log('e -->>', e)
				const _this = this;
				// 获取图片的宽高
				const file = e.tempFiles;
				this.canvasWidthValue = file[0].image.width;
				this.canvasHeightValue = file[0].image.height;
				// 将时间和位置信息添加到文件对象中
				file[0].currentLocation = this.location;
				const pixelRatio = uni.getSystemInfo().pixelRatio; //获取像素比
				// 创建一个临时canvas对象  query
				const query = uni.createSelectorQuery()
				query.select('#myCanvas').fields({
						node: true,
						size: true
					})
					.exec(res => {
						const canvas = res[0].node
						const ctx = canvas.getContext('2d');
						const img = canvas.createImage()
						img.src = file[0].path
						img.onload = function() {
							//设置画布到校绘制原图到canvas中 

							ctx.canvas.width = file[0].image.width;
							ctx.canvas.height = file[0].image.height;
							// ctx.drawImage(img, 0, 0, file[0].image.width / 2, file[0].image.height / 2)
							ctx.drawImage(img, 0, 0, file[0].image.width, file[0].image.height)

							// 设置水印字体大小、颜色和位置 
							ctx.font = "30px arial";
							ctx.fillStyle = "#FFFFFF";
							ctx.textAlign = "left";
							ctx.textBaseline = "bottom";
							// 绘制时间和位置信息到canvas中
							ctx.fillText(_this.formatTime(new Date()), 10, 60);
							ctx.fillText(_this.currentLocationAreaText, 10, 95);
							ctx.fillText(_this.location, 10, 128);
							// 将canvas转换成图片，并将其添加到文件对象中
							uni.canvasToTempFilePath({
								canvas: canvas,
								quality: 1,
								width: file[0].image.width,
								height: file[0].image.heigh,
								success: (res) => {
									file[0].path = res.tempFilePath;
									console.log("res --- 含水印 ------->>> ", res)
									console.log("file --- 含水印 ------->>> ", file)
									// 上传包含水印的图片
									tool_oss.oss.upload(file, this.fileLimit).then(
										res => {
											console.log('res ---->>>', res);
											const fileObj = {
												name: res.fileUploadSuccessObj
													.name,
												url: res.fileUploadSuccessObj.url
											};

											// 回显
											console.log("fileObj ----》》》", fileObj)
											_this.baseFormData.photo = fileObj;

										})
								},
							});
						}
					})
			},

			// 提交需求
			handleSubmit() {
				const _this = this;
				this.$refs.baseForm.validate((err, formData) => {
					if (!err) {
						let postData = formData;
						postData.imageUrl = formData.photo.url;

						_this.typeList.filter(item => {
							if (item.value === formData.problemType) {
								postData.problemType = item.text;
							}
						})
						postData.gis = _this.location;
						postData.addr = _this.currentLocationAreaText;
						console.log("post ------->>>>", postData);
						this.postWorksheetPublicApi(postData);
					}
				});
			},

			// 创建新的公益工作单
			postWorksheetPublicApi(postData) {
				postWorksheetPublic(postData).then(res => {
					console.log('res ---->>>', res)
					if (res.code === 200) {
						uni.showModal({
							title: '提示',
							content: '操作成功！',
							success: function(res) {
								if (res.confirm) {
									uni.navigateBack()
								}
							}
						});
					}
				})
			}
		}
	}
</script>

<style>
	.uni-easyinput__placeholder-class {
		opacity: 0.3;
		font-family: PingFangSC-Regular;
		font-weight: 400;
		font-size: 30rpx;
		color: #1E1F23;
	}
</style>

<style lang="scss">
	.public-welfare-page {
		position: relative;
		z-index: 99;
		padding: 20rpx 2.66vw;
		overflow: auto;
		box-sizing: border-box;
		width: 100%;

		.uni-forms-item.is-direction-top .uni-forms-item__label {
			padding-bottom: 0;
		}

		.public-welfare-page-group {
			// overflow: auto;
			background-color: #fff;
			margin-top: 20rpx;
			border-radius: 20rpx;
			padding: 18rpx 24rpx;

			&.forms-item-line {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.uni-forms-item {
					width: 50%;
				}

				.rt {
					width: 50%;
					text-align: right;
					display: flex;
					justify-content: flex-end;
					align-items: center;
					// padding-bottom: 8px;
				}
			}

			.example-group {
				margin-top: 28rpx;

				.tit {
					height: 42rpx;
					font-family: PingFangSC-Regular;
					font-weight: 400;
					font-size: 30rpx;
					color: #05073B;
					margin-bottom: 6rpx;
				}

				.imgs {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.img {
						width: 164rpx;
						height: 120rpx;
						border-radius: 16rpx;
						margin-right: 12rpx;

						&:last-child {
							margin-right: 0;
						}
					}
				}

			}

			.uni-forms-item {
				margin: 0;

				.uni-forms-item__label {
					color: #000;
				}

				.file-title {
					color: #999;
				}

				.uni-easyinput__content-textarea {
					width: 100%;
					height: 100% !important;
					font-family: PingFangSC-Regular;
					font-weight: 400;
					font-size: 30rpx;
					color: #1E1F23;
					padding: 12rpx 24rpx;
					box-sizing: border-box;
				}

				.file-picker__box-content {
					width: 102px;
					height: 102px;
					background: #F5F6FA;
					border-radius: 4px;

					.add-img-icon-group {
						opacity: 0.3;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;

						.add-img-icon {
							width: 26px;
							height: 26px;
						}

						.add-img-text {
							font-family: PingFangSC-Regular;
							font-weight: 400;
							font-size: 13px;
							color: #1E1F23;
						}
					}


				}
			}

			.uni-list-item__container {
				height: 35px;
				line-height: 35px;
			}

			.is-add,
			.uni-easyinput__content {
				background-color: #F5F6FA !important;
				width: 662rpx;
				height: 424rpx;
				border-radius: 16rpx;
			}

			.uni-data-checklist .checklist-group {
				justify-content: space-around;

				.checklist-box {
					box-sizing: border-box;
					width: 200rpx;
					height: 64rpx;

					.checklist-content {
						justify-content: center;
					}
				}

				.checklist-box.is--tag {
					margin-right: 0;
				}
			}
		}

		.submit {
			width: 100%;
			height: auo;
			margin-top: 10px;

			.btn-submit {
				width: 94.67vw;
				height: 45px;
				background: #22A366;
				border-radius: 8px;
				color: #fff;
				font-weight: 400;
				font-size: 17px;
			}
		}
	}
</style>